import http from "@/services"
import { message } from "antd";
// umi中存储history 这个属性，方法中使用useHistory获取到其history
import { history } from "umi"
export default {
    state: {
        user: localStorage.getItem("userProfile") ? JSON.parse(localStorage.getItem("userProfile")) : null
    },
    reducers: {
        setUser(state, { payload }) {
            return payload;
        },
        setRouteList(state, { payload }) {
            return {
                ...state,
                routeList: payload
            }
        },
        removeUser() {
            return null;
        }
    },
    effects: {
        *login({ payload }, { put, call, select }) {
            const result = yield call(http.Login, payload);
            if (result.data) {
                message.success(result.msg)
                yield put({
                    type: "setUser",
                    payload: result.data
                });
                localStorage.setItem("userProfile", JSON.stringify(result.data));
                const routeData = yield call(http.getRouteList);
                if (routeData.data) {
                    localStorage.setItem("routeList", JSON.stringify(routeData.data));
                    // 存储routeList
                    yield put({
                        type: "setRouteList",
                        payload: routeData.data
                    });
                    // 界面跳转
                    history.push(routeData.data[0].route);
                } else {
                    message.error(routeData.msg);
                }
            } else {
                message.error(result.msg);
            }
        }
    }
}